#include "Heap.h"

void Swap(HPDataType* x1, HPDataType* x2)
{
	HPDataType k = *x1;
	*x1 = *x2;
	*x2 = k;
}

void AdjustUp(HPDataType* a, int child)
{
	assert(a);
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void AdjustDown(HPDataType* a, int parent, int n)
{
	assert(a);
	HPDataType child = 2 * parent + 1;
	while (child < n)
	{
		if (child < n && a[child + 1] > a[child])
		{
			child++;
		}
		if (a[parent] < a[child])
		{
			Swap(&a[parent], &a[child]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void HeapPrint(Heap* hp)
{
	assert(hp);
	for (int i = 0; i < hp->_size; i++)
	{
		printf("%d ", hp->_a[i]);
	}
	printf("\n");
}

void HeapSort(Heap* hp)
{
	assert(hp);
	assert(hp->_size);
	int end = hp->_size - 1;
	while (end)
	{
		Swap(&hp->_a[end], &hp->_a[0]);
		end--;
		AdjustDown(hp->_a, 0, end);
	}
}

void HeapInit(Heap* hp)
{
	assert(hp);
	hp->_a = NULL;
	hp->_size = 0;
	hp->_capacity = 0;
}

void HeapCreate(Heap* hp, HPDataType* a, int n)
{
	assert(hp);
	assert(a);
	for (int i = 0; i < n; i++)
	{
		HeapPush(hp, a[i]);
	}
}

void HeapDestory(Heap* hp)
{
	assert(hp);
	free(hp->_a);
	hp->_a = NULL;
	hp->_size = 0;
	hp->_capacity = 0;
}

void HeapPush(Heap* hp, HPDataType x)
{
	assert(hp);
	if (hp->_capacity == hp->_size)
	{
		hp->_capacity = (hp->_capacity == 0 ? 4 : hp->_capacity * 2);
		HPDataType* ret = (HPDataType*)realloc(hp->_a, sizeof(HPDataType) * hp->_capacity);
		if (ret == NULL)
		{
			perror("realloc");
			exit(-1);
		}
		hp->_a = ret;
	}
	hp->_a[hp->_size] = x;
	hp->_size++;
	AdjustUp(hp->_a, hp->_size - 1);
}

void HeapPop(Heap* hp)
{
	assert(hp);
	assert(hp->_size);
	Swap(&hp->_a[0], &hp->_a[hp->_size - 1]);
	hp->_size--;
	AdjustDown(hp->_a, 0, hp->_size);
}

HPDataType HeapTop(Heap* hp)
{
	assert(hp);
	assert(hp->_size);
	return hp->_a[0];
}

int HeapSize(Heap* hp)
{
	assert(hp);
	return hp->_size;
}

int HeapEmpty(Heap* hp)
{
	assert(hp);
	if (hp->_size == 0)
	{
		return 1;
	}
	return 0;
}
